import 'package:flutter/material.dart';

class MyGrid extends StatelessWidget {
  final List<Widget> children;
  final int columnCount;
  final double spacing;
  final double runSpacing;

  const MyGrid({
    Key? key,
    required this.children,
    required this.columnCount,
    this.spacing = 8.0,
    this.runSpacing = 8.0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Widget> rows = [];

    // 每行 columnCount 个
    for (int i = 0; i < children.length; i += columnCount) {
      final end = (i + columnCount < children.length)
          ? i + columnCount
          : children.length;
      final rowItems = children.sublist(i, end);

      // 如果不足列数，补空 Expanded 占位
      while (rowItems.length < columnCount) {
        rowItems.add(const Expanded(child: SizedBox()));
      }

      rows.add(
        Padding(
          padding: EdgeInsets.only(bottom: runSpacing),
          child: Row(
            children: List.generate(columnCount, (index) {
              return Expanded(
                child: Padding(
                  padding: EdgeInsets.only(
                    right: index == columnCount - 1 ? 0 : spacing,
                  ),
                  child: index < rowItems.length ? rowItems[index] : const SizedBox(),
                ),
              );
            }),
          ),
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: rows,
    );
  }
}
